using System;
using System.Data;
using System.Collections;
using APP.QUANLY.Entity;
using APP.QUANLY.Entity.ConditionForm;

namespace APP.QUANLY.DAL
{
    /// <summary>
    /// Summary description for QUANLYTHETHEOKHACHHANG.
     /// </summary>
	public class QUANLYTHETHEOKHACHHANGDao
    {
	    private string _SQLSelectByKey;
	    private string _SQLUpdate;
	    private string _SQLInsert;
	    private string _SQLDelete;
	    private string _SQLSelectAll;

        #region Properties

        public IDbConnection _dbConnection;

        public IDbConnection DbConnection
        {
            get { return _dbConnection; }
            set { _dbConnection = value; }
        }

        #endregion
        
        #region Constructor

        public QUANLYTHETHEOKHACHHANGDao()
        {
            _dbConnection = null;
		    InitSqlQuery();
        }

        public QUANLYTHETHEOKHACHHANGDao(IDbConnection con)
        {
            _dbConnection = con;
            InitSqlQuery();
        }

        #endregion


        private void ToLowerQuery()
        {
            _SQLDelete = _SQLDelete.ToLower();
            _SQLUpdate = _SQLUpdate.ToLower();
            _SQLInsert = _SQLInsert.ToLower();
            _SQLSelectByKey = _SQLSelectByKey.ToLower();
        }

        private void ToUpperQuery()
        {
            _SQLDelete = _SQLDelete.ToUpper();
            _SQLUpdate = _SQLUpdate.ToUpper();
            _SQLInsert = _SQLInsert.ToUpper();
            _SQLSelectByKey = _SQLSelectByKey.ToUpper();
        }

        #region InitSqlQuery
        private void InitSqlQuery()
       {
            string query;

            query = @"SELECT KHCARDMANAGERID, MAKHACHHANG, MATHE, NGAYCAPTHE, NGAYHETHANTHE, NGAYMUADAUTIEN, NGAYMUACUOICUNG, TONGTICHLUY, STATUS, ISUSE, ISDELETE FROM QUANLYTHETHEOKHACHHANG WHERE (KHCARDMANAGERID = @KHCARDMANAGERID)";
	        _SQLSelectByKey = query;

            query = @"UPDATE QUANLYTHETHEOKHACHHANG SET MAKHACHHANG = @MAKHACHHANG, MATHE = @MATHE, NGAYCAPTHE = @NGAYCAPTHE, NGAYHETHANTHE = @NGAYHETHANTHE, NGAYMUADAUTIEN = @NGAYMUADAUTIEN, NGAYMUACUOICUNG = @NGAYMUACUOICUNG, TONGTICHLUY = @TONGTICHLUY, STATUS = @STATUS, ISUSE = @ISUSE, ISDELETE = @ISDELETE WHERE (KHCARDMANAGERID = @KHCARDMANAGERID)";
	        _SQLUpdate = query;

            query = @"INSERT INTO QUANLYTHETHEOKHACHHANG VALUES (@KHCARDMANAGERID, @MAKHACHHANG, @MATHE, @NGAYCAPTHE, @NGAYHETHANTHE, @NGAYMUADAUTIEN, @NGAYMUACUOICUNG, @TONGTICHLUY, @STATUS, @ISUSE, @ISDELETE)";
	        _SQLInsert = query;

            query = @"DELETE FROM QUANLYTHETHEOKHACHHANG WHERE (KHCARDMANAGERID = @KHCARDMANAGERID)";
	        _SQLDelete = query;

            query = @"SELECT KHCARDMANAGERID, MAKHACHHANG, MATHE, NGAYCAPTHE, NGAYHETHANTHE, NGAYMUADAUTIEN, NGAYMUACUOICUNG, TONGTICHLUY, STATUS, ISUSE, ISDELETE FROM QUANLYTHETHEOKHACHHANG";
	        _SQLSelectAll = query;
        }
        #endregion
        public void LoadByCommandText(string commandtext, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = commandtext;

				if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        #region Save & Delete
        private void Save(QUANLYTHETHEOKHACHHANG obj, IDbTransaction trans, bool isExisting)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                command = _dbConnection.CreateCommand();

                if (!isExisting) { command.CommandText = _SQLInsert + ";"; }
                else { command.CommandText = _SQLUpdate + ";"; }

                         DalTools.addDbDataParameter(command, "KHCARDMANAGERID", obj.KHCARDMANAGERID, DbType.Int32);
                         DalTools.addDbDataParameter(command, "MAKHACHHANG", obj.MAKHACHHANG, DbType.Guid);
         DalTools.addDbDataParameter(command, "MATHE", obj.MATHE, DbType.String);
         DalTools.addDbDataParameter(command, "NGAYCAPTHE", obj.NGAYCAPTHE, DbType.DateTime);
         DalTools.addDbDataParameter(command, "NGAYHETHANTHE", obj.NGAYHETHANTHE, DbType.DateTime);
         DalTools.addDbDataParameter(command, "NGAYMUADAUTIEN", obj.NGAYMUADAUTIEN, DbType.DateTime);
         DalTools.addDbDataParameter(command, "NGAYMUACUOICUNG", obj.NGAYMUACUOICUNG, DbType.DateTime);
         DalTools.addDbDataParameter(command, "TONGTICHLUY", obj.TONGTICHLUY, DbType.Decimal);
         DalTools.addDbDataParameter(command, "STATUS", obj.STATUS, DbType.Int32);
         DalTools.addDbDataParameter(command, "ISUSE", obj.ISUSE, DbType.Boolean);
         DalTools.addDbDataParameter(command, "ISDELETE", obj.ISDELETE, DbType.Boolean);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Delete(QUANLYTHETHEOKHACHHANG obj, IDbTransaction trans)
        {
            if (_dbConnection == null)
            {
                //throw new DalException("Connection has not been set.");
                throw new Exception("Connection has not been set.");
            }

            IDbCommand command;

            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }

                command = _dbConnection.CreateCommand();
                command.CommandText = _SQLDelete + ";";

                         DalTools.addDbDataParameter(command, "KHCARDMANAGERID", obj.KHCARDMANAGERID, DbType.Int32);

		        if (trans != null) { command.Transaction = trans; }
                if (command.ExecuteNonQuery() == 0) { throw new Exception("Zero rows were affected."); }
            }
            catch (Exception ex) { throw ex; }
        }

        public void Insert(QUANLYTHETHEOKHACHHANG obj, IDbTransaction trans)
        {
            Save(obj, trans, false);
        }
        public void Update(QUANLYTHETHEOKHACHHANG obj, IDbTransaction trans)
        {
            Save(obj, trans, true);
        }
        #endregion

        #region Command Execute & Read Properties
     
        private QUANLYTHETHEOKHACHHANGList SelectListByCommand(IDbCommand command)
        {
            QUANLYTHETHEOKHACHHANGList list = new QUANLYTHETHEOKHACHHANGList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				QUANLYTHETHEOKHACHHANG obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new QUANLYTHETHEOKHACHHANG();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }
		
        private QUANLYTHETHEOKHACHHANGList SelectListByCommand(IDbCommand command, IDbTransaction trans)
        {
            QUANLYTHETHEOKHACHHANGList list = new QUANLYTHETHEOKHACHHANGList();
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {	
				QUANLYTHETHEOKHACHHANG obj;
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
				command.Transaction = trans;
                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read()) 
					{ 
						obj = new QUANLYTHETHEOKHACHHANG();
						ReadProperties(obj, reader);
						list.Add(obj); 
					}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }

        private void DeleteListByCommand(IDbCommand command, IDbTransaction trans)
        {
            if (_dbConnection == null) { throw new Exception("Connection has not been set."); }
            try
            {
                if (_dbConnection.State != ConnectionState.Open) { _dbConnection.Open(); }
                if (trans != null) { command.Transaction = trans; }
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
	
        private void ReadProperties(QUANLYTHETHEOKHACHHANG obj, IDataReader reader)
        {
            try
            {
                                if(!(reader["KHCARDMANAGERID"] is DBNull))
		{
			obj.KHCARDMANAGERID = (Int32)reader["KHCARDMANAGERID"];
		}
                if(!(reader["MAKHACHHANG"] is DBNull))
		{
			obj.MAKHACHHANG = (Guid)reader["MAKHACHHANG"];
		}
                if(!(reader["MATHE"] is DBNull))
		{
			obj.MATHE = (string)reader["MATHE"];
		}
                if(!(reader["NGAYCAPTHE"] is DBNull))
		{
			obj.NGAYCAPTHE = (DateTime)reader["NGAYCAPTHE"];
		}
                if(!(reader["NGAYHETHANTHE"] is DBNull))
		{
			obj.NGAYHETHANTHE = (DateTime)reader["NGAYHETHANTHE"];
		}
                if(!(reader["NGAYMUADAUTIEN"] is DBNull))
		{
			obj.NGAYMUADAUTIEN = (DateTime)reader["NGAYMUADAUTIEN"];
		}
                if(!(reader["NGAYMUACUOICUNG"] is DBNull))
		{
			obj.NGAYMUACUOICUNG = (DateTime)reader["NGAYMUACUOICUNG"];
		}
                if(!(reader["TONGTICHLUY"] is DBNull))
		{
			obj.TONGTICHLUY = (decimal)reader["TONGTICHLUY"];
		}
                if(!(reader["STATUS"] is DBNull))
		{
			obj.STATUS = (Int32)reader["STATUS"];
		}
                if(!(reader["ISUSE"] is DBNull))
		{
			obj.ISUSE = (bool)reader["ISUSE"];
		}
                if(!(reader["ISDELETE"] is DBNull))
		{
			obj.ISDELETE = (bool)reader["ISDELETE"];
		}
            }
            catch (Exception ex)
            {
                throw new DalException("Failed to read properties from DataReader.", ex);
            }
        }
        #endregion
      
        public QUANLYTHETHEOKHACHHANG SelectByKey(Int32 KHCARDMANAGERID)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "KHCARDMANAGERID", KHCARDMANAGERID, DbType.Int32);
      	    QUANLYTHETHEOKHACHHANGList list =  SelectListByCommand(command);

            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }

        public QUANLYTHETHEOKHACHHANG SelectByKey(Int32 KHCARDMANAGERID, IDbTransaction trans)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectByKey;
	                 DalTools.addDbDataParameter(command, "KHCARDMANAGERID", KHCARDMANAGERID, DbType.Int32);
      	    QUANLYTHETHEOKHACHHANGList list =  SelectListByCommand(command, trans);
			
            if (list.Count == 0) { throw new Exception("No data was returned"); }
            return list[0];
        }
		
        public QUANLYTHETHEOKHACHHANGList SelectAll()
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = _SQLSelectAll;
      	    QUANLYTHETHEOKHACHHANGList list =  SelectListByCommand(command);
	        return list;
        }

         public QUANLYTHETHEOKHACHHANGList SelectByCommand(string Command)
        {
            IDbCommand command  = _dbConnection.CreateCommand();
            command.CommandText = Command;
      	    QUANLYTHETHEOKHACHHANGList list =  SelectListByCommand(command);
	        return list;
        }

        public QUANLYTHETHEOKHACHHANGList SelectByCondition(QUANLYTHETHEOKHACHHANGConditionForm condt)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "SELECT * FROM QUANLYTHETHEOKHACHHANG " + GetCondtionQuery(condt) + ";";
            FillParamToCommand(command, condt);
            QUANLYTHETHEOKHACHHANGList list = SelectListByCommand(command);
            return list;
        }

        private void DeleteByCondition(QUANLYTHETHEOKHACHHANGConditionForm condt, IDbTransaction trans)
        {
            IDbCommand command = _dbConnection.CreateCommand();
            command.CommandText = "DELETE FROM QUANLYTHETHEOKHACHHANG " + GetCondtionQuery(condt) + ";";
            FillParamToCommand(command, condt);
            DeleteListByCommand(command, trans);
        }

        #region Make Condition Query & Fill Param from Condition to Command
        private string GetCondtionQuery(QUANLYTHETHEOKHACHHANGConditionForm obj)
        {
            if (obj == null) { return ""; }
            string s = "";
            	if (obj.IsSetKHCARDMANAGERID)
	{
    	    s += " AND KHCARDMANAGERID = @KHCARDMANAGERID ";
	}
	if (obj.IsSetMAKHACHHANG)
	{
    	    s += " AND MAKHACHHANG = @MAKHACHHANG ";
	}
	if (obj.IsSetMATHE)
	{
    	    s += " AND MATHE = @MATHE ";
	}
	if (obj.IsSetNGAYCAPTHE)
	{
    	    s += " AND NGAYCAPTHE = @NGAYCAPTHE ";
	}
	if (obj.IsSetNGAYHETHANTHE)
	{
    	    s += " AND NGAYHETHANTHE = @NGAYHETHANTHE ";
	}
	if (obj.IsSetNGAYMUADAUTIEN)
	{
    	    s += " AND NGAYMUADAUTIEN = @NGAYMUADAUTIEN ";
	}
	if (obj.IsSetNGAYMUACUOICUNG)
	{
    	    s += " AND NGAYMUACUOICUNG = @NGAYMUACUOICUNG ";
	}
	if (obj.IsSetTONGTICHLUY)
	{
    	    s += " AND TONGTICHLUY = @TONGTICHLUY ";
	}
	if (obj.IsSetSTATUS)
	{
    	    s += " AND STATUS = @STATUS ";
	}
	if (obj.IsSetISUSE)
	{
    	    s += " AND ISUSE = @ISUSE ";
	}
	if (obj.IsSetISDELETE)
	{
    	    s += " AND ISDELETE = @ISDELETE ";
	}
            if (s.Length > 0)
            {
                s =" WHERE "+s.Substring(4);
                return s;
            }
            return "";
        }

        private void FillParamToCommand(IDbCommand command, QUANLYTHETHEOKHACHHANGConditionForm obj)
        {
	    if (obj == null) { return;}
            	            if (obj.IsSetKHCARDMANAGERID)
            {
            	DalTools.addDbDataParameter(command, "KHCARDMANAGERID", obj.KHCARDMANAGERID, DbType.Int32); 
            }
            if (obj.IsSetMAKHACHHANG)
            {
            	DalTools.addDbDataParameter(command, "MAKHACHHANG", obj.MAKHACHHANG, DbType.Guid); 
            }
            if (obj.IsSetMATHE)
            {
            	DalTools.addDbDataParameter(command, "MATHE", obj.MATHE, DbType.String); 
            }
            if (obj.IsSetNGAYCAPTHE)
            {
            	DalTools.addDbDataParameter(command, "NGAYCAPTHE", obj.NGAYCAPTHE, DbType.DateTime); 
            }
            if (obj.IsSetNGAYHETHANTHE)
            {
            	DalTools.addDbDataParameter(command, "NGAYHETHANTHE", obj.NGAYHETHANTHE, DbType.DateTime); 
            }
            if (obj.IsSetNGAYMUADAUTIEN)
            {
            	DalTools.addDbDataParameter(command, "NGAYMUADAUTIEN", obj.NGAYMUADAUTIEN, DbType.DateTime); 
            }
            if (obj.IsSetNGAYMUACUOICUNG)
            {
            	DalTools.addDbDataParameter(command, "NGAYMUACUOICUNG", obj.NGAYMUACUOICUNG, DbType.DateTime); 
            }
            if (obj.IsSetTONGTICHLUY)
            {
            	DalTools.addDbDataParameter(command, "TONGTICHLUY", obj.TONGTICHLUY, DbType.Decimal); 
            }
            if (obj.IsSetSTATUS)
            {
            	DalTools.addDbDataParameter(command, "STATUS", obj.STATUS, DbType.Int32); 
            }
            if (obj.IsSetISUSE)
            {
            	DalTools.addDbDataParameter(command, "ISUSE", obj.ISUSE, DbType.Boolean); 
            }
            if (obj.IsSetISDELETE)
            {
            	DalTools.addDbDataParameter(command, "ISDELETE", obj.ISDELETE, DbType.Boolean); 
            }
        }
        #endregion
    }
}